<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id ? "编辑企业" : "添加企业" }}</span>
      </div>
      <div class="right">黑马程序员</div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="addForm" label-width="100px" :model="addForm" :rules="rules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in IndustryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- action 为必传属性，配置的上传文件的路径，不灵活不用 -->
              <!-- action 即使不用，也得用#代替上传路径 -->
              <!-- :before-upload 校验通过才会执行 :http-request 绑定的方法 -->
              <el-upload
                class="upload-demo"
                action="#"
                :http-request="uploadImage"
                :before-upload="beforeUpload"
                :limit="1"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传 .jpg .png .jpeg 文件，且不超过5M
                </div>
              </el-upload>
              <img
                v-if="addForm.businessLicenseUrl"
                :src="addForm.businessLicenseUrl"
                style="width: 100px"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm('addForm')">重置</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import {
  getIndustryListAPI,
  addEnterpriseAPI,
  getEnterpriseDetailAPI,
  updateExterpriseAPI,
} from "@/api/enterprise";
import { uploadFileAPI } from "@/api/common";
export default {
  data() {
    return {
      addForm: {
        name: "", // 企业名称
        legalPerson: "", // 法人
        registeredAddress: "", // 注册地址
        industryCode: "", // 所在行业
        contact: "", // 企业联系人
        contactNumber: "", // 联系人电话
        businessLicenseUrl: "", // 营业执照url
        businessLicenseId: "", // 营业执照id
      },
      fileList: [], // 用于存储上传文件的列表
      IndustryList: [],
      rules: {
        name: [{ required: true, message: "企业名称为必填", trigger: "blur" }],
        legalPerson: [{ required: true, message: "法人为必填", trigger: "blur" }],
        registeredAddress: [{ required: true, message: "注册地址为必填", trigger: "blur" }],
        industryCode: [{ required: true, message: "所在行业为必填", trigger: "change" }],
        contact: [{ required: true, message: "企业联系人为必填", trigger: "blur" }],
        contactNumber: [
          { required: true, message: "企业联系人电话为必填", trigger: "blur" },
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
        businessLicenseId: [{ required: true, message: "请上传营业执照", trigger: "change" }],
      },
    };
  },
  computed: {
    id() {
      // 获取路由传递的参数
      // this.route.params.xx  动态路由方式
      return this.$route.query.id; // 查询参数方式
    },
  },
  created() {
    this.getIndustryList(); // 页面加载时获取行业列表
    if (this.id) {
      this.getEnterpriseDetail();
    }
  },
  methods: {
    // 获取企业详情
    async getEnterpriseDetail() {
      const { data } = await getEnterpriseDetailAPI(this.id);
      this.addForm = data;
      if (data.businessLicenseUrl) {
        this.fileList = [
          {
            name: data.businessLicenseName || "营业执照",
            url: data.businessLicenseUrl,
          },
        ];
      }
    },
    // 表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.handleRemove();
    },
    // 表单提交兜底校验/提交
    confirmAdd() {
      this.$refs.addForm.validate(async (flag) => {
        if (!flag) return;
        if (this.id) {
          // delete 对象名.属性名  删除对象中的属性
          delete this.addForm.rent;
          delete this.addForm.industryName;
          delete this.addForm.businessLicenseName;
          await updateExterpriseAPI(this.addForm);
        } else {
          delete this.addForm.businessLicenseName;
          await addEnterpriseAPI(this.addForm);
        }
        this.$message.success(this.id ? "编辑成功" : "添加成功");
        this.$router.back();
      });
    },
    // 上传文件校验
    beforeUpload(file) {
      const allowImgType = ["image/jpeg", "image/png", "image/jpg"].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!allowImgType) {
        this.$message.error("上传图片只能是 PNG/JPG/JPEG 格式!");
        return false;
      }
      if (!isLt5M) {
        this.$message.error("上传图片大小不能超过 5MB!");
        return false;
      }
      return allowImgType && isLt5M;
    },
    // 上传文件
    async uploadImage({ file }) {
      // 创建后端需要的 application/form-data 对象
      const formDate = new FormData();
      // formDate 追加数据 使用 append('键',值)方法
      formDate.append("file", file);
      formDate.append("type", 1);
      // 配合 on-success
      try {
        const { data } = await uploadFileAPI(formDate);
        return { data }; // 返回的结构要符合on-success回调的预期 ✅
      } catch (error) {
        console.error("上传失败:", error);
        return Promise.reject(error);
      }
      // 注意：上传文件不是一般的表单元素，不能直接通知el-form校验，而是单独校验
      // this.$refs.addForm.validateField("businessLicenseId");
    },
    // on-success上传成功
    handleSuccess(response, file) {
      this.addForm.businessLicenseId = response.data.id;
      this.addForm.businessLicenseUrl = response.data.url;
      this.addForm.businessLicenseName = file.name;
      this.$refs.addForm.validateField("businessLicenseId");
    },
    // 上传文件超出个数提示
    handleExceed() {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    // 移出上传文件
    handleRemove() {
      this.addForm.businessLicenseId = null;
      this.addForm.businessLicenseUrl = null;
      this.addForm.businessLicenseName = null;
      this.fileList = []; // 清空文件列表
      this.$refs.addForm.validateField("businessLicenseId");
    },
    // 获取行业列表
    async getIndustryList() {
      const { data } = await getIndustryListAPI();
      this.IndustryList = data;
    },
  },
};
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
